<template>
  <div class="pagination">
    <button @click="$emit('get-nextpage',pageNo-1)" :disabled="pageNo === 1">上一页</button>
    <button v-show="startAndEnd.start > 1" @click="$emit('change-pageNo',1)">1</button>
    <button v-show="startAndEnd.start > 2" >...</button>
    <!-- <button>{{startAndEnd.start}}</button> -->
    <button
      :class="{ active: startAndEnd.start + index === pageNo }"
      v-for="(_, index) in startAndEnd.end - startAndEnd.start + 1"
      :key="_"
      @click="$emit('change-pageNo',startAndEnd.start+index)"
    >
      {{ startAndEnd.start + index }}
    </button>
    <!-- <button>{{startAndEnd.end}}</button> -->
    <button v-show="startAndEnd.end < totalPage - 2">···</button>
    <button v-show="startAndEnd.end < totalPage" @click="$emit('change-pageNo',totalPage)">{{ totalPage }}</button>
    <button @click="$emit('get-nextpage',pageNo+1)" :disabled="pageNo === totalPage">下一页</button>
    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  // 总数量、展示条数、连续页面、当前页面
  props: ["total", "pageSize", "continues", "pageNo"],
  // methods:{
  //   //点击切换高亮
  //   savePage(){

  //   }
  // },
  computed: {
    // 1.计算总页码
    totalPage() {
      const { total, pageSize } = this;
      return Math.ceil(total / pageSize);
    },
    // 2.计算连续页码的开始页和结束页
    startAndEnd() {
      //先解构出来当前页码和连续页码
      const { continues, pageNo, totalPage } = this;
      //根据当前页码计算前后的对称页码
      let start, end;
      // 2.1特殊情况，连续页码大于总页码，起始页是1，结束页是totalPage
      //  比如，总数量是91条数量，但是一页要显示30条，则只需要4页即可
      // 但是连贯页码却是5，当前页码是3，应该如何？ 1234
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + Math.trunc(continues / 2);
        // 2.2 特殊情况二 当起始页小于1的时候 则起始页只能等于1 结束页就是continues
        if (start < 1) {
          start = 1;
          end = continues;
        }

        // 2.3 特殊情况三 当结束页超过了总页码  则结束页只能是总页码
        if (end > totalPage) {
          //25 26 27 28 29 30 31
          end = totalPage;
          start = totalPage - continues + 1;
        }
      }
      // 2.2
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 38px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>